package com.zheng.current.controller;

import com.zheng.current.ParallelTasker;
import com.zheng.current.dto.Task;
import com.zheng.current.dto.WrapFlightQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author: ztl
 * @date: 2025/06/22 22:33
 * @desc:
 */

@RestController
@RequestMapping("/cur")
public class TestController {
    private Logger logger = LoggerFactory.getLogger(TestController.class);
    @PostMapping("/test")
    public void test1(){
        // 创建线程工厂，下面要用
        ThreadFactory threadFactory = r -> {
            Thread thread = new Thread(r,"test-zheng-"+System.currentTimeMillis());
            thread.setDaemon(false);
            return thread;
        };
        // 创建线程池
        ThreadPoolExecutor executor =new ThreadPoolExecutor(40, 40,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
                threadFactory,
                new ThreadPoolExecutor.AbortPolicy());
        // 新建公共查询条件，任务那要用
        WrapFlightQuery query = new WrapFlightQuery();
        query.setNonGw(true);

        // 新建任务
        List<ParallelTasker> taskList = new ArrayList<>();
        List<String> channelList = Arrays.asList("CQ","IBE");
        for (String channel : channelList){
            if (Task.IBE.getValue().equals(channel)){
                ParallelTasker tasker = new ParallelTasker(query,Task.IBE);
                taskList.add(tasker);
            }
            if (Task.CQ.getValue().equals(channel)){
                ParallelTasker tasker = new ParallelTasker(query,Task.CQ);
                taskList.add(tasker);
            }

        }

        long start = System.currentTimeMillis();
        try {

            // 执行任务
            List<Future<Map<String, Object>>> futures = executor.invokeAll(taskList, 8, TimeUnit.SECONDS);
            long end = System.currentTimeMillis();
            logger.info("并发执行完毕了，共耗时：",(end-start)/1000);
        } catch (InterruptedException e) {
            logger.error("发送从上；",e);
            throw new RuntimeException(e);
        }catch (Exception e) {
            logger.error("发送从上111；",e);
            throw new RuntimeException(e);
        }
        long end = System.currentTimeMillis();
        logger.info("aaaa全部执行完毕了，共耗时：",(end-start)/1000);
    }
}
